package by.grsu.crs.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import by.grsu.crs.form.SignInForm;
import by.grsu.crs.service.AuthenticationService;
import by.grsu.crs.service.impl.AuthenticationServiceImpl;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class SignInAction extends Action {
    private final static String SUCCESS = "success";
    private final static String FAILURE = "failure";

    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        SignInForm signInForm = (SignInForm) form;
        AuthenticationService authService = new AuthenticationServiceImpl();
        
        if (authService.signIn(signInForm.getEmail(), signInForm.getPassword(), signInForm.isRememberMe())) {
            return mapping.findForward(SUCCESS);
        } else {
        	ActionErrors errors = new ActionErrors();
            errors.add("password", new ActionMessage("error.password.wrong-password"));
            this.saveErrors(request, errors);
            
            return mapping.findForward(FAILURE);
        }
    }
}
